﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Forum.BLL.Member;
using Forum.Web.BaseCode;
using Forum.Entity.Member;
using Forum.Web.Models;

using Forum.Web.Filters;
using Forum.BLL.Group;
using Forum.Entity.Group;
using Frame.Lib.Utilities;
using Frame.Lib.Core.Log;

namespace Forum.Web.Controllers
{
    public class MemberController : BaseController
    {
        //
        // GET: /Member/

        public ActionResult Index()
        {
            return View();
        }


        public ContentResult Exist(string field, string value)
        {
            MemberBaseBO member = new MemberBaseBO();
            bool flag = member.ExistField(field, value, null);
            if (flag)
            {
                return Content("true");
            }
            else
            {
                return Content("false");
            }
        }

        public ActionResult Register()
        {
            if (!string.IsNullOrEmpty(Request["ErrorMessage"]))
            {
                this.ViewData["initjs"] = "setMessage('" + Request["ErrorMessage"] + "',false);";
            }
           
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Add()
        {
            string validateCode = Request.Form["ValidateCode"];

            if (validateCode.ToLower() != WebSession.ValidateCode.ToLower())
            {
                return RedirectToAction("Register", new { ErrorMessage = "验证码错误" });
            }


            MemberBaseInfo baseMemberInfo = new MemberBaseInfo();
            baseMemberInfo.LoginName = Request.Form["LoginName"];
            baseMemberInfo.Password = StrUtil.EncryptMD5(Request.Form["Password"]);
            baseMemberInfo.Email = Request.Form["Email"];
            baseMemberInfo.Name = baseMemberInfo.LoginName;
            baseMemberInfo.State = (int)MemberState.正常;

            MemberBaseBO memberBase = new MemberBaseBO();
            if (memberBase.ExistField("LoginName", baseMemberInfo.LoginName, null))
            {
                return RedirectToAction("Register", new { ErrorMessage = "用户名已存在" });
            }

            if (memberBase.ExistField("Email", baseMemberInfo.Email, null))
            {
                return RedirectToAction("Register", new { ErrorMessage = "电子邮件已存在" });
            }

            MemberExBO forumMember = new MemberExBO();
            forumMember.dbOper = memberBase.dbOper;
            try
            {
                forumMember.dbOper.BeginTrans();

                memberBase.Save(baseMemberInfo);

                MemberExInfo memberInfo = new MemberExInfo();
                memberInfo.RegisterTime = memberInfo.LastPostTime = memberInfo.LastVisitTime = DateTime.Now;
                memberInfo.ID = baseMemberInfo.ID;

                GroupBO group = new GroupBO();
                GroupInfo groupInfo = group.GetList().Where(T => T.TypeID == (int)GroupType.积分组).OrderBy(T => T.CreditMin).FirstOrDefault();
                if (groupInfo != null)
                {
                    memberInfo.GroupID = groupInfo.ID;
                    memberInfo.GroupName = groupInfo.Name;
                }

                forumMember.Save(memberInfo, true);

                forumMember.dbOper.CommitTrans();


                base.MemberInfo.MemberID = baseMemberInfo.ID;
                base.MemberInfo.MemberLoginName = baseMemberInfo.LoginName;
                base.MemberInfo.Save();
               

                return RedirectToAction("Index", "Home");                
            }
            catch (Exception ex)
            {
                Logger.Exception(ex);
                forumMember.dbOper.RollbackTrans();
                return RedirectToAction("Register", new { ErrorMessage = "注册失败" });
            }
        }


        public ActionResult TopLogin()
        {

            if (base.MemberInfo.IsLogin)
            {
                return View(ForumPath.Views + "Member/Shared/TopLogin.cshtml", base.MemberInfo);              
            }
            else
            {
                return View(ForumPath.Views + "Member/Shared/TopUnLogin.cshtml");
            }
        }

        public RedirectResult DoLogin()
        {
            string loginName = Request.Form["LoginName"];
            string password = Request.Form["Password"];

            MemberBaseBO member = new MemberBaseBO();
            MemberBaseInfo info = member.GetInfoByLoginName(loginName);
            if (info != null && info.Password == StrUtil.EncryptDES(password))
            {               
                base.MemberInfo.MemberID = info.ID;
                base.MemberInfo.MemberLoginName = loginName;
                base.MemberInfo.Save();                
            }
            else
            {
                this.ViewBag.Message = "用户名或密码错";
            }
                
            string url = Request.UrlReferrer.AbsolutePath;

            return this.Redirect(url);
        }

        public ViewResult Login()
        {

            return View(ForumPath.Views + "Member/Login.cshtml");
        }

        public RedirectResult Logout()
        {
            base.MemberInfo.Clear();

            string url = Request.UrlReferrer.AbsolutePath;

            return this.Redirect(url);
        }

        [CheckLoginFilter]
        public ViewResult BaseInfo()
        {
            BaseInfoModel model = new BaseInfoModel();
            model.LeftIndex = 2;
            return View(ForumPath.Views + "Member/BaseInfo.cshtml", model);
        }

    }
}
